package com.bwie.snyc;

import com.alibaba.fastjson.JSON;
import com.bwie.common.domain.Student;
import com.bwie.common.remote.system.RemoteEsService;
import com.bwie.common.result.Result;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @Author：ShenJiaFeng
 * @Package：com.bwie.snyc
 * @Project：zg5_19
 * @name：EsSync
 * @Date：2024/2/18 8:54
 */
@Component
public class EsSync {
    private final RestHighLevelClient client;
    public static String INDEX_NAME="student";
    private final RemoteEsService remoteEsService;

    public EsSync(RestHighLevelClient client, RemoteEsService remoteEsService) {
        this.client = client;

        this.remoteEsService = remoteEsService;
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void add(){
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(INDEX_NAME);
        deleteByQueryRequest.setQuery(QueryBuilders.matchAllQuery());

        /**
         * 执行删除
         */
        try {
            client.deleteByQuery(deleteByQueryRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Result<List<Student>> listResult = remoteEsService.studentLists();
        List<Student> students = listResult.getData();

        BulkRequest bulkRequest = new BulkRequest();
        for (Student student : students) {
            IndexRequest stu = new IndexRequest(INDEX_NAME).id(student.getStudentId() + "").source(JSON.toJSONString(student), XContentType.JSON);
            bulkRequest.add(stu);
        }
        try {
            client.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
